import tkinter as tk
from tkinter import ttk, messagebox
import random
import pandas as pd
import numpy as np


class DoubleColorBallApp:
    def __init__(self, root):
        self.root = root
        self.root.title("双色球机选程序")
        self.root.geometry("800x600")

        # 模拟历史数据（实际可从CSV/数据库读取，这里生成100期模拟数据）
        self.historical_data = self.generate_simulated_history(100)

        # 界面组件
        self.create_widgets()

    def generate_simulated_history(self, num_periods):
        """生成模拟历史数据：红球(6个1-33不重复) + 蓝球(1个1-16)"""
        history = []
        for _ in range(num_periods):
            red = sorted(random.sample(range(1, 34), 6))
            blue = random.randint(1, 16)
            history.append({"red": red, "blue": blue})
        return history

    def analyze_history(self):
        """分析历史数据：统计红球、蓝球频次，奇偶分布等"""
        red_counts = np.zeros(33, dtype=int)
        blue_counts = np.zeros(16, dtype=int)
        red_odd_even = {"odd": 0, "even": 0}
        red_intervals = {
            "1-11": 0, "12-22": 0, "23-33": 0
        }

        for data in self.historical_data:
            # 统计红球频次、奇偶、区间
            for num in data["red"]:
                red_counts[num - 1] += 1
                if num % 2 == 1:
                    red_odd_even["odd"] += 1
                else:
                    red_odd_even["even"] += 1
                if 1 <= num <= 11:
                    red_intervals["1-11"] += 1
                elif 12 <= num <= 22:
                    red_intervals["12-22"] += 1
                else:
                    red_intervals["23-33"] += 1
            # 统计蓝球频次
            blue_counts[data["blue"] - 1] += 1

        # 计算频次排名（从低到高，优先选低频但非冷号）
        red_freq_rank = sorted(range(33), key=lambda i: red_counts[i])
        blue_freq_rank = sorted(range(16), key=lambda i: blue_counts[i])

        return {
            "red_counts": red_counts,
            "blue_counts": blue_counts,
            "red_odd_even": red_odd_even,
            "red_intervals": red_intervals,
            "red_freq_rank": [i + 1 for i in red_freq_rank],  # 转换为实际号码(1-33)
            "blue_freq_rank": [i + 1 for i in blue_freq_rank]  # 转换为实际号码(1-16)
        }

    def generate_reasonable_number(self, num_notes):
        """生成“有道理”的号码：结合历史数据的频次、奇偶、区间特征"""
        analysis = self.analyze_history()
        results = []

        for _ in range(num_notes):
            # 选红球：从低频排名中选6个不重复，同时控制奇偶比例(3奇3偶左右)
            red_candidates = analysis["red_freq_rank"][:20]  # 取低频前20个候选
            red_selected = []
            odd_count = 0
            even_count = 0
            while len(red_selected) < 6:
                candidate = random.choice(red_candidates)
                if candidate not in red_selected:
                    if candidate % 2 == 1:
                        if odd_count < 4:  # 最多4奇
                            red_selected.append(candidate)
                            odd_count += 1
                    else:
                        if even_count < 4:  # 最多4偶
                            red_selected.append(candidate)
                            even_count += 1
            red_sorted = sorted(red_selected)

            # 选蓝球：从低频排名中选1个
            blue_selected = random.choice(analysis["blue_freq_rank"][:5])  # 取蓝球低频前5个

            results.append({"red": red_sorted, "blue": blue_selected})

        return results

    def create_widgets(self):
        """创建界面组件"""
        # 标题
        title_frame = tk.Frame(self.root)
        title_frame.pack(pady=10)
        tk.Label(title_frame, text="双色球智能机选程序", font=("微软雅黑", 18)).pack()

        # 按钮区域
        button_frame = tk.Frame(self.root)
        button_frame.pack(pady=20)
        ttk.Button(button_frame, text="机选五注", command=lambda: self.show_result(5)).pack(side=tk.LEFT, padx=10)
        ttk.Button(button_frame, text="机选十注", command=lambda: self.show_result(10)).pack(side=tk.LEFT, padx=10)

        # 结果展示区域
        result_frame = tk.Frame(self.root)
        result_frame.pack(fill=tk.BOTH, expand=True, padx=20, pady=10)
        self.result_text = tk.Text(result_frame, wrap=tk.WORD, font=("微软雅黑", 10))
        self.result_text.pack(fill=tk.BOTH, expand=True)
        scrollbar = tk.Scrollbar(self.result_text, command=self.result_text.yview)
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        self.result_text.config(yscrollcommand=scrollbar.set)

    def show_result(self, num_notes):
        """生成并展示号码结果"""
        self.result_text.delete(1.0, tk.END)
        results = self.generate_reasonable_number(num_notes)

        for i, result in enumerate(results, 1):
            red_str = " ".join(f"{num:02d}" for num in result["red"])
            blue_str = f"{result['blue']:02d}"
            self.result_text.insert(tk.END, f"第{i}注：红球[{red_str}] 蓝球[{blue_str}]\n")



if __name__ == "__main__":
    root = tk.Tk()
    app = DoubleColorBallApp(root)
    root.mainloop()